from flask import Flask, render_template_string
import qrcode
import json

app = Flask(__name__)

# 读取配置文件设备数据
def load_devices():
    with open("devices.json", "r", encoding="utf-8") as f:
        return json.load(f)

devices = load_devices()

HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <title>设备信息 - {{ device.name }}</title>
    <style>
        body { font-family: Arial, sans-serif; background: #f0f2f5; padding: 2em; }
        .container {
            max-width: 400px;
            background: white;
            margin: auto;
            padding: 2em;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0,0,0,0.1);
        }
        h1 { margin-bottom: 0.5em; color: #333; }
        p { font-size: 16px; margin: 0.5em 0; color: #555; }
        .status-online { color: green; font-weight: bold; }
        .status-offline { color: red; font-weight: bold; }
    </style>
</head>
<body>
    <div class="container">
        <h1>设备名称：{{ device.name }}</h1>
        <p><strong>位置：</strong>{{ device.location }}</p>
        <p><strong>状态：</strong>
            {% if device.status == '在线' %}
                <span class="status-online">{{ device.status }}</span>
            {% else %}
                <span class="status-offline">{{ device.status }}</span>
            {% endif %}
        </p>
    </div>
</body>
</html>
"""

@app.route("/device/<int:device_id>")
def get_device(device_id):
    device = devices.get(str(device_id))
    if device:
        return render_template_string(HTML_TEMPLATE, device=device)
    return "<h2>设备不存在</h2>", 404

if __name__ == "__main__":
    url = "http://8.141.10.90:5000/device/123"  # 改成你ECS服务器公网IP或内网IP
    img = qrcode.make(url)
    img.save("device_123.png")
    print(f"已生成二维码 device_123.png，内容: {url}")

    app.run(host="0.0.0.0", port=5000)
